<template>
  <!-- 没有地方获取生产单号 -->
  <!-- 产线前看板 -->
  <div class="app-container">
    <div class="search-bar">
      <el-form
        ref="queryFormRef"
        :model="queryParams"
        :rules="basketRule"
        :inline="true"
        label="100px"
      >
        <el-form-item label="生产单号">
          <el-select v-model="queryParams.code" placeholder="请输入生产单号" class="!w-44">
            <el-option
              v-for="item in productionOrderOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="筐号" prop="basket">
          <el-input
            v-noSpace
            v-model="queryParams.basket"
            placeholder="请输入筐号"
            class="!w-64"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="scanProdBasket">确认</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="flex justify-center" v-if="product">
      <div
        class="bg-white border border-gray-200 rounded-lg p-6 hover:shadow-lg transition-shadow duration-300 w-full max-w-lg"
      >
        <div class="space-y-4">
          <!-- 筐码 -->
          <div class="flex items-start">
            <el-icon class="text-blue-600 mt-1"><Stamp /></el-icon>
            <div class="ml-3">
              <div class="text-sm text-gray-500">筐码</div>
              <div class="font-mono text-lg font-semibold text-gray-900">
                {{ product?.parentCode }}
              </div>
            </div>
          </div>
          <!-- 产品编号 -->
          <div class="flex items-start">
            <el-icon class="text-blue-600 mt-1"><Document /></el-icon>
            <div class="ml-3">
              <div class="text-sm text-gray-500">产品编号</div>
              <div class="font-mono text-lg text-gray-900">
                {{ product?.productCode }}
              </div>
            </div>
          </div>
          <!-- 产品名称 -->
          <div class="flex items-start">
            <el-icon class="text-blue-600 mt-1"><Box /></el-icon>
            <div class="ml-3">
              <div class="text-sm text-gray-500">产品名称</div>
              <div class="text-lg text-gray-900">{{ product?.productName }}</div>
            </div>
          </div>
          <!-- 产品重量 -->
          <div class="flex items-start">
            <el-icon class="text-blue-600 mt-1"><ScaleToOriginal /></el-icon>
            <div class="ml-3">
              <div class="text-sm text-gray-500">产品重量</div>
              <div class="text-lg font-medium text-gray-900">{{ product?.qty }} kg</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import prodOrderManageApi, { prodOrderScanParams } from "@/api/prodManage/prodOrderManage";
import { FormItemRule } from "element-plus";
import { reactive, ref } from "vue";
const queryParams = reactive<prodOrderScanParams>({
  code: "",
  basket: "",
});
const ScanPatternType = {
  BASKET_CODE: /^[Ww]\d+$|^[Ss]\d{13}$/,
  /**
   * 筐码规则：以s开头的13位时间戳；产品编号（PRO开头）；产品名称（汉字可能有数字和特殊字符）；重量（数字，可能有小数）;单位（例如：kg）;采购订单;供应商 示例：s1650729600000;PRO123456;苹果（非转基因）;1.5;kg;pur1332333;美团
   */
  BASKET_CODE_TIMESTAMP:
    /^s\d{13};PRO\d+;[\u4e00-\u9fa5a-zA-Z0-9]+;\d+(?:\.\d+)?;[a-zA-Z\u4e00-\u9fa5]+;(?:pur|tou|prt|order)\d+;[\u4e00-\u9fa5a-zA-Z]+$/i,
};

const validateBasket = (rule: any, value: string, callback: Function) => {
  if (ScanPatternType.BASKET_CODE.test(value)) {
    callback();
  } else {
    console.log(ScanPatternType.BASKET_CODE.test(value));
    callback(new Error("请输入正确的筐号"));
  }
};

const basketRule: Record<string, FormItemRule[]> = {
  basket: [
    {
      required: true,
      message: "请输入筐号",
    },
    {
      validator: validateBasket,
      message: "请输入正确的筐号(w101/S2503210000007)",
      trigger: "blur",
    },
  ],
};

// 生产单号选项，这里需要根据实际情况从后端获取
const productionOrderOptions = ref();

//产品信息
const product = ref<{
  productName: string;
  qty: number;
  parentCode: string;
  productCode: string;
}>();

const scanProdBasket = () => {
  //校验

  console.log("生产单号:", queryParams.code);
  console.log("筐号:", queryParams.basket);
  prodOrderManageApi
    .scanProdBasket(queryParams)
    .then((res) => {
      console.log(res, "扫描成功");
      product.value = res;
    })
    .catch((err) => {
      product.value = undefined;
      // errorNotification(err);
    });
};

//处理扫码逻辑
const handleScan = (code: string) => {
  if (ScanPatternType.BASKET_CODE_TIMESTAMP.test(code)) {
    // 处理时间戳格式的扫码数据
    console.log("处理时间戳格式的扫码数据:", code);
    queryParams.basket = code.split(";")[0]; // 假设时间戳格式的扫码数据中，生产单号位于第6个分号之后
  } else if (ScanPatternType.BASKET_CODE.test(code)) {
    // 处理普通筐码格式的扫码数据
    queryParams.basket = code;
  }
};

//查询生产单
const handleQuery = () => {
  // 这里可以添加查询逻辑，例如调用API获取数据
  prodOrderManageApi.getPage({ pageNum: 1, pageSize: 999, statusList: [5] }).then((res) => {
    productionOrderOptions.value = res.list?.map((item: any) => ({
      value: item.code,
      label: item.code,
    }));
  });
};

//错误通知
const errorNotification = (message: string) => {
  ElNotification({
    title: "Error",
    message: message,
    type: "error",
    duration: 5000,
    offset: 50,
  });
};
onMounted(() => {
  handleQuery();
});
</script>

<style scoped></style>
